package cn.tedu.javagame.ball;

import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.util.List;
import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class BallPanel extends JPanel implements MouseMotionListener {
    Board board = new Board();
    List<Ball> balls = new ArrayList<>();
    List<Brick> bricks = new ArrayList<>();
    public BallPanel() {
        //对鼠标进行监听注册
        this.addMouseMotionListener(this);
        for (int i = 0; i < 10; i++) {
            balls.add(new Ball());
        }
        for (int i = 0; i < 50; i++) {
            bricks.add(new Brick(i%10*192,i/10*62));
        }
    }
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        for (int i = 0; i < balls.size(); i++) {
            Ball ball = balls.get(i);
            g.setColor(ball.color);
            g.fillOval(ball.x, ball.y, ball.length, ball.length);
        }
        g.setColor(Color.black);
        g.fillRect(board.x,board.y,board.width,board.height);
        for (int i = 0; i < bricks.size(); i++) {
            Brick brick = bricks.get(i);
            g.setColor(brick.color);
            g.fillRect(brick.x,brick.y,brick.width,brick.height);
        }
    }
    public void action(){
        Timer timer =new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                for(int i=0;i<balls.size();i++){
                    Ball ball = balls.get(i);
                    ball.move();
                }
                boardAndBall();
                ballAndBrick();
                repaint();
            }
        }, 0, 10);
    }
    public void ballAndBrick(){
        //循环遍历得到每一个小球，再遍历到每一个砖块
        for(int i=0;i<balls.size();i++){
            Ball ball = balls.get(i);
            for(int j=0;j<bricks.size();j++){
                Brick brick = bricks.get(j);
                if(ball.hitBrick(brick)){
                    brick.hit();
                    if (ball.state == 0) ball.state = 3;
                    else if (ball.state == 1) ball.state = 2;
                    else if (ball.state == 2) ball.state = 1;
                    else if (ball.state == 3) ball.state = 0;
                    if(brick.height <= 0){bricks.remove(j);}
                }
            }
        }
    }
    public void boardAndBall(){
        //循环遍历每一个小球，都与挡板进行判断
        for (int i = 0; i < balls.size(); i++) {
            Ball ball = balls.get(i);
            board.catchBall(ball);
        }
    }

    @Override
    public void mouseDragged(MouseEvent e) {

    }

    @Override
    public void mouseMoved(MouseEvent e) {
        board.move(e.getX());
    }
}
